Is there a way to create a unique id over 2 fields?

您所在的位置:网站首页 django save_model create Is there a way to create a unique id over 2 fields?

Is there a way to create a unique id over 2 fields?

2023-04-20 13:54| 来源: 网络整理| 查看: 265

I explain several options here, maybe one of them or a combination can be useful for you.

Overriding save

Your constraint is a business rule, you can override save method to keep data consistent:

class GroupedModels(models.Model): # ... def clean(self): if (self.other_model_one.pk == self.other_model_two.pk): raise ValidationError({'other_model_one':'Some message'}) if (self.other_model_one.pk < self.other_model_two.pk): #switching models self.other_model_one, self.other_model_two = self.other_model_two, self.other_model_one # ... def save(self, *args, **kwargs): self.clean() super(GroupedModels, self).save(*args, **kwargs) Change design

I put a sample easy to understand. Let's suppose this scenario:

class BasketballMatch(models.Model): local = models.ForeignKey('app.team') visitor = models.ForeignKey('app.team')

Now, you want to avoid a team playing a match with itself also team A only can play with team B for once (almost your rules). You can redesign your models as:

class BasketballMatch(models.Model): HOME = 'H' GUEST = 'G' ROLES = [ (HOME, 'Home'), (GUEST, 'Guest'), ] match_id = models.IntegerField() role = models.CharField(max_length=1, choices=ROLES) player = models.ForeignKey('app.other_model') class Meta: unique_together = [ ( 'match_id', 'role', ) , ( 'match_id', 'player',) , ] ManyToManyField.symmetrical

This look like a symetrical issue, django can handle it for you. Instead of create GroupedModels model, just make a ManyToManyField field with itself on OtherModel:

from django.db import models class OtherModel(models.Model): ... grouped_models = models.ManyToManyField("self")

This is what django has as built in for these scenarios.

It's not a very satisfying answer, but unfortunately the truth is there is no way to do what you're describing with a simple built-in feature.

What you described with clean would work, but you have to be careful to manually call it as I think it's only automatically called when using ModelForm. You might be able to create a complex database constraint but that would live outside of Django and you'd have to handle database exceptions (which can be difficult in Django when in the middle of a transaction).

Maybe there's a better way to structure the data?



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3